﻿using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraTab;
using Lamex.Base;
using Lamex.Library;
using Lamex.Library.CommonClass;
using Lamex.SIESystemManager.BLL;
using Lamex.SIESystemManager.Calculate;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;


namespace Lamex.SIESystemManager.UI
{
    public partial class FrmBIEOperationDataSJ : frmBaseDataForm
    {
        List<string> errorList = new List<string>();//保存错误值
        int sucess = 0, fail = 0, sumCount = 0;    
        int angle = 0;//旋转角度
        PictureBox pic = new PictureBox();//标准图片
        PictureBox picSJ = new PictureBox();//SJ图片
        XtraTabPage Page = new XtraTabPage();
        Bitmap myBmp;//图片定义
        Point mouseDownPoint = new Point(); //记录拖拽过程鼠标位置
        bool isMove = false;    //判断鼠标在picturebox上移动时，是否处于拖拽过程(鼠标左键是否按下)
        int zoomStep = 75;      //缩放步长
        private static Dictionary<string, XtraTabPage> TabPageDic = new Dictionary<string, XtraTabPage>();
        private static Dictionary<string, PictureBox> PictureDic = new Dictionary<string, PictureBox>();
        private static Dictionary<string, Bitmap> BitDic = new Dictionary<string, Bitmap>();
        private static Dictionary<string, XtraTabPage> TabPageDicSJ = new Dictionary<string, XtraTabPage>();
        private static Dictionary<string, PictureBox> PictureDicSJ = new Dictionary<string, PictureBox>();
        private static Dictionary<string, Bitmap> BitDicSJ = new Dictionary<string, Bitmap>();
        string drawNum = "";
        public FrmBIEOperationDataSJ()
        {
            InitializeComponent();
            InitializeForm();
            this.Load += new EventHandler(FrmBIEOperationDataSJ_Load);

        }
        public string IsEdit = "";
        public string KeysName = "";
        string DrawNumdelete = "";
        protected override void InitializeForm()
        {
            DataTable dt = new DataTable();         
            dt = BaseFactory<B_IE_SJR_DATA>.Instance.SJDataSet().Tables[0];
            gcViewAll.DataSource = dt;
         
            ShowSummary(); //下载显示数据.              
            ucAutoAddControls1.GetTableInfo();
        }
        private void FrmBIEOperationDataSJ_Load(object sender, EventArgs e)
        {
            try { this.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
        }
        private void ShowSummary()
        {
            try
            {
                //
                //ucLookUpEdit1.ValueMember = "UserName";
                //ucLookUpEdit1.DisPlayMember = "UserName";
                //ucLookUpEdit1.DataSource = dt;
                ////ucLookUpEdit1.UcPopulateColumns();

                ////ucLookUpEdit1.Item[1].Caption = "用户名称";
                //////ucLookUpEdit1.ForceInitialize();
                ////ucLookUpEdit1.UcItemIndex = 0;
                //DoBindingSummaryGrid(dt); //绑定主表的Grid
                //ShowSummaryPage(true); //显示Summary页面. 
                xtraTabPage2.PageEnabled = false;
                xtraTabPage1.PageEnabled = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        public override void DoAdd(Lamex.Interface.IButtonInfo sender)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("B_IE_Operation_Data", "LamexMESManager")) return;
            #endregion
            xtraTabPage1.PageEnabled = false;
            xtraTabPage2.PageEnabled = true;
            xtraTabPage2.PageVisible = true;
            IsEdit = "新增";
            xtraTabPage2.Tag = "新增";
            base.DoAdd(sender);
            txtEditDRAWING_NUMBER.Focus();
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        public override void DoView(Lamex.Interface.IButtonInfo sender)
        {
            //string sqlWhere = "";
            //string sql = " select * from B_IE_Operation_Data where 1=1 ";
            //if (!string.IsNullOrEmpty(txtDRAWING_NUMBER.Text))
            //{
            //    sqlWhere += " and DRAWING_NUMBER like '%" + txtDRAWING_NUMBER.Text + "%'";
            //}
            //if (!string.IsNullOrEmpty(txtPART_NO.Text))
            //{
            //    sqlWhere += " and COMPONENT_TYPE like '%" + txtPART_NO.Text + "%'";
            //}
            //sql = sql + sqlWhere;
            //DataTable dt = BaseFactory<B_IE_Operation_Data>.Instance.GetDataTableBySql(sql);
            //DoBindingSummaryGrid(dt);
            base.DoView(sender);

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        public override void DoDelete(Lamex.Interface.IButtonInfo sender)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("B_IE_Operation_Data", "LamexMESManager")) return;
            #endregion
            if (gridView2.SelectedRowsCount == 0)
            {
                MessageBox.Show("【没有选中要删除的数据，请选择好数据！】");
                return;
            }
            int m = gridView2.FocusedRowHandle;
            DataRow dr = gridView2.GetDataRow(m);
            if (dr != null)
            {
                if (BaseFactory<B_IE_Operation_Data>.Instance.Delete(dr["IDNO"].ToString()))
                {
                    MessageBox.Show("【数据删除成功！】");

                }
                else
                {
                    MessageBox.Show("【数据删除失败！】");

                }
            }
            DoView(null);
            base.DoDelete(sender);
        }
        private void txtEditDRAWING_NUMBER_KeyDown(object sender, KeyEventArgs e)
        {

            ucAutoAddControls1.Claer();
            ucAutoAddControls1.DrawingNumber = txtEditDRAWING_NUMBER.Text;
            ucAutoAddControls1.userName = Lamex.Common.Loginer.CurrentUser.Account;
        }
        //刷新
        public void ReFresh()
        {
            txtEditDRAWING_NUMBER.Text = "";
            txtEditNUMBER1.Text = "";
            txtEditNUMBER2.Text = "";
            txtEditNUMBER3.Text = "";
            txtEditNUMBER4.Text = "";
            txtEditNUMBER5.Text = "";
            txtEditNUMBER6.Text = "";
            txtEditNUMBER7.Text = "";
            txtEditNUMBER8.Text = "";
            txtEditNUMBER9.Text = "";
            txtEditNUMBER10.Text = "";
            txtEditDRAWING_NUMBER.Focus();
        }
        //返回
        public override void DoReturn(Lamex.Interface.IButtonInfo sender)
        {
            #region 清空控件值
            int tabCount5 = this.xtraTabControl5.TabPages.Count;
            int tabCount4 = this.xtraTabControl4.TabPages.Count;
            for (int i = tabCount4 - 1; i >= 0; i--)
            {

                this.xtraTabControl4.TabPages.RemoveAt(i);

            }
            for (int i = tabCount5 - 1; i >= 0; i--)
            {

                this.xtraTabControl5.TabPages.RemoveAt(i);

            }
            Page = new XtraTabPage();
            pic = new PictureBox();
            TabPageDic = new Dictionary<string, XtraTabPage>();
            TabPageDicSJ = new Dictionary<string, XtraTabPage>();
            PictureDic = new Dictionary<string, PictureBox>();
            PictureDicSJ = new Dictionary<string, PictureBox>();
            BitDic = new Dictionary<string, Bitmap>();
            BitDicSJ = new Dictionary<string, Bitmap>();
            txtEditDRAWING_NUMBER.Text = "";
            #endregion
            if (!string.IsNullOrEmpty(drawNum))
            {
                string sql = "";
                sql = @"update B_IE_SJR_DATA set locked=0 where PartNo='" + drawNum + "'";
                int m = BaseBuildSql.ExecuteNonQuery(sql);
            }
            base.DoReturn(sender);
        }
        #region"加载控件"
        DevExpress.XtraEditors.TextEdit editControl = null;
        string workProcess = "";
        public void LoadItem(DevExpress.XtraEditors.TextEdit textEdit)
        {
            if (string.IsNullOrEmpty(txtEditDRAWING_NUMBER.Text))
            {
                XtraMessageBox.Show("图纸号为空，无法加载项目");
                return;
            }
            Lamex.SIESystemManager.Model.B_IE_SJR_DATAInfo model = BaseFactory<B_IE_SJR_DATA>.Instance.GetEntriyList(" 1=1 and PartNo='" + txtEditDRAWING_NUMBER.Text + "'").FirstOrDefault();
            string sJdrawNum = "";
            if (model != null)
            {
                sJdrawNum = model.Drawing_No;
            }

            DataTable dt = BaseFactory<B_IE_Operation_Data>.Instance.GetDataTableBySql("select * from B_IE_Operation_Data where DRAWING_NUMBER='" + sJdrawNum + "'");
            DataTable sjdt = BaseFactory<B_IE_Operation_Data>.Instance.GetDataTableBySql("select * from B_IE_Operation_Data_TempSJ where DRAWING_NUMBER='" + txtEditDRAWING_NUMBER.Text + "'");
            string[] strArr = textEdit.Text.Split('_');
            if (strArr.Count() > 0)
            {
                string flag = "";
                editControl = textEdit;
                workProcess = strArr[0];
                ucAutoAddControls1.LoadListImtes(strArr[0], editControl, txtEditDRAWING_NUMBER.Text);
                if (sjdt.Rows.Count == 0)
                {

                    if (dt.Rows.Count != 0)
                    {
                        flag = "1";
                        ucAutoAddControls1.LoadData(sJdrawNum, Lamex.Common.Loginer.CurrentUser.Account, DateTime.Now.ToString(), workProcess, editControl, flag);
                    }
                    else
                    {
                        ucAutoAddControls1.LoadData(txtEditDRAWING_NUMBER.Text, Lamex.Common.Loginer.CurrentUser.Account, DateTime.Now.ToString(), workProcess, editControl, "");
                    }
                }
                else
                {
                    //int m_value = ucAutoAddControls1.ReturnValue(txtEditDRAWING_NUMBER.Text, Lamex.Common.Loginer.CurrentUser.Account, DateTime.Now.ToString(), workProcess, editControl);
                    //if (m_value == 0 && sjdt.Rows.Count == 0)
                    //    ucAutoAddControls1.LoadData(sJdrawNum, Lamex.Common.Loginer.CurrentUser.Account, DateTime.Now.ToString(), workProcess, editControl, "1");
                    //else
                    ucAutoAddControls1.LoadData(txtEditDRAWING_NUMBER.Text, Lamex.Common.Loginer.CurrentUser.Account, DateTime.Now.ToString(), workProcess, editControl, "");
                }
            }

        }

        private void txtEditNUMBER1_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER1);
        }
        private void txtEditNUMBER2_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER2);
        }

        private void txtEditNUMBER3_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER3);
        }

        private void txtEditNUMBER4_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER4);
        }

        private void txtEditNUMBER5_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER5);
        }

        private void txtEditNUMBER6_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER6);
        }

        private void txtEditNUMBER7_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER7);
        }

        private void txtEditNUMBER8_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER8);
        }

        private void txtEditNUMBER9_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER9);
        }

        private void txtEditNUMBER10_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER10);
        }

        private void txtEditNUMBER11_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER11);
        }

        private void txtEditNUMBER12_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER12);
        }

        private void txtEditNUMBER13_Click(object sender, EventArgs e)
        {
            LoadItem(txtEditNUMBER13);
        }
        #endregion
        //保存
        public override void DoSave(Lamex.Interface.IButtonInfo sender)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("B_IE_Operation_Data", "LamexMESManager")) return;
            #endregion
            try
            {
                using (DevExpress.Utils.WaitDialogForm wdf = new DevExpress.Utils.WaitDialogForm("请稍等", "正在保存中......", new Size(400, 80)))
                {
                    List<string> list = new List<string>();
                    int[] rownumber = this.gridView2.GetSelectedRows();//获取选中行号；
                                                                       //单个保存
                    if (!string.IsNullOrEmpty(txtEditDRAWING_NUMBER.Text))
                    {
                        list.Add(txtEditDRAWING_NUMBER.Text);
                        List<string> strProcessList = new List<string>();
                        foreach (Control c in panelControl9.Controls)
                        {
                            if (c is TextEdit)
                            {
                                TextEdit t = c as TextEdit;
                                if (c.Name != "txtEditDRAWING_NUMBER")
                                {
                                    //if(c.Enabled==true)
                                    //{
                                    string[] arrItems = c.Text.Split('_');
                                    strProcessList.Add(arrItems[0]);
                                    //}
                                }
                            }
                        }
                        if (ucAutoAddControls1.SaveAllList(txtEditDRAWING_NUMBER.Text, strProcessList))
                        {
                            xtraTabPage2.PageEnabled = false;
                            xtraTabPage1.PageEnabled = true;

                            xtraTabControl3.TabPages.Clear();
                            xtraTabControl2.TabPages.Clear();
                            foreach (Control c in panelControl9.Controls)
                            {
                                if (c is TextEdit)
                                {
                                    TextEdit t = c as TextEdit;
                                    t.Text = "";
                                    t.Enabled = true;

                                }
                            }
                        }
                        else
                            list = new List<string>();
                    }
                    //批量保存
                    else if (rownumber.Length > 0)
                    {
                        foreach (var item in rownumber)
                        {
                            DataRow row = this.gridView2.GetDataRow(item);//根据行号获取相应行的数据；
                            List<string> strProcessList = new List<string>();
                            strProcessList.Add("SJPL");
                            list.Add(row[1].ToString());
                            if (ucAutoAddControls1.SaveAllList(row[1].ToString(), strProcessList))
                            {
                                //成功保存后转移到历史表
                            }
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("图纸号为空或导入数据为空，无法加载保存项目");
                        return;
                    }
                    if (list.Count > 0)
                    {
                        //计算保存
                        DoCalculate(list);
                        DevExpress.XtraEditors.XtraMessageBox.Show("共【" + list.Count + "】条！成功【" + sucess + "】条！失败【" + fail + "】条！", "提示", MessageBoxButtons.OK);
                        if (errorList.Count > 0)
                        {
                            StringBuilder sbFilter = new StringBuilder();
                            StringBuilder sbFilter2 = new StringBuilder();
                            sbFilter.AppendFormat(@"  PartNo IN ('{0}')", string.Join("','", errorList.ToArray()));
                            sbFilter2.AppendFormat(@"  Mater_No IN ('{0}')", string.Join("','", errorList.ToArray()));
                            string sql2 = @"update [LamexMESManager].[dbo].[B_IE_SJR_DATA]  set LockMan='" + Lamex.Common.Loginer.CurrentUser.Account + "',Locked=1,Flag=NULL, Calculate_Flag=NULL ,Calculate_TS=NULL where 1=1 AND " + sbFilter + " ";
                            BaseFactory<B_IE_SJData_Import>.Instance.ExecuteNonQuery(sql2);
                            //导出错误列表
                            if (!Directory.Exists(@"D:\MESTemp"))
                                Directory.CreateDirectory(@"D:\MESTemp");
                            SaveFileDialog fileDialog = new SaveFileDialog();
                            fileDialog.Title = "导出错误列表";
                            fileDialog.InitialDirectory = @"D:\MESTemp\";//导出默认路径
                            fileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";//导出默认格式
                            fileDialog.FileName = "MES_TEMP_" + DateTime.Now.ToString("yyMMdd_hhMMss");//导出默认名称                                                                                                                               
                            string sql = @"SELECT distinct
       [Mater_No] as PartNo
      ,[Drawing_No]
      ,[Describes]
      --,[Create_TS]
  FROM[LamexMESManager].[dbo].[B_IE_BOM_ERRORINFO]
  where 1=1 AND " + sbFilter2 + " ";
                            DataTable dtTemp = BaseBuildSql.GetDataTableBySql(sql);
                            GridControl grid = new GridControl();
                            GridView view = new GridView();
                            grid.ViewCollection.Add(view);
                            grid.MainView = view;
                            view.GridControl = grid;
                            foreach (DataColumn dc in dtTemp.Columns)
                            {
                                DevExpress.XtraGrid.Columns.GridColumn gridColumnNumber = view.Columns.AddVisible(dc.ColumnName);
                                gridColumnNumber.FieldName = dc.ColumnName;
                            }
                            grid.DataSource = dtTemp;
                            this.Controls.Add(grid);
                            grid.ForceInitialize();//强制初始化           
                            view.BestFitColumns();
                            view.OptionsView.ColumnAutoWidth = false;
                            view.OptionsView.ShowAutoFilterRow = false;
                            view.OptionsPrint.PrintHorzLines = false;//去掉水平网格线
                            view.OptionsPrint.PrintVertLines = false;//去掉垂直网格线
                            view.ExportToXlsx(fileDialog.InitialDirectory + fileDialog.FileName + ".xlsx");
                            //if (DevExpress.XtraEditors.XtraMessageBox.Show("生成错误信息列表成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                            System.Diagnostics.Process.Start(fileDialog.InitialDirectory + fileDialog.FileName + ".xlsx");//打开指定路径下的文件

                        }
                        sucess = 0;
                        fail = 0;
                        sumCount = 0;
                        errorList = new List<string>();
                        ClearPic();
                        InitializeForm();
                        base.DoSave(sender);
                    }
                    ////执行储存过程--工时数据更新到IE_Part_ProcessTime
                    //List<string> lst1 = new List<string>();
                    //lst1.Add("1");
                    //BaseBuildSql.GetProDataTable("p_IE_IED_TransForm", lst1);
                }
            }
            catch (Exception EX)
            {

                XtraMessageBox.Show("保存失败！" + EX.Message);
            }

        }
        /// <summary>
        /// 工时计算
        /// </summary>
        /// <param name="sender"></param>
        public void DoCalculate(List<string> listP)
        {
            #region 前台计算
            //一定要选择时间


            GetSqlData gd = new GetSqlData();
            GetOperation_Data gOperate = new GetOperation_Data();
            C_D04 c_d04 = new C_D04();
            C_D07 c_d07 = new C_D07();
            C_D11 c_d11 = new C_D11();
            C_D14 c_d14 = new C_D14();
            C_D21 c_d21 = new C_D21();
            C_D24 c_d24 = new C_D24();
            C_D27 c_d27 = new C_D27();
            C_D28 c_d28 = new C_D28();
            C_D29 c_d29 = new C_D29();
            C_D30 c_d30 = new C_D30();
            C_D31 c_d31 = new C_D31();
            C_D32 c_d32 = new C_D32();
            C_D34 c_d34 = new C_D34();
            C_D37 c_d37 = new C_D37();
            C_D41 c_d41 = new C_D41();
            C_D42 c_d42 = new C_D42();
            C_BOM_Routing c_Bom = new C_BOM_Routing();
            C_Routing_Group c_routing = new C_Routing_Group();
            GetWorkHourTable dt = new GetWorkHourTable();
            // DataTable dtWork_Time = gOperate.GetIEWorkTime_SJ();//工时保存表

            int failNull = 0;
            List<string> LS1 = new List<string>();
            int Serial = 0, Routing_Group = 0, Calculate = 0;//代码组和流水号计数
            List<double> RoutingList = new List<double>();//代码组描述
            bool first = true;//用于判断是否第一次执行
            string Routing_dec = "";
            double TD01 = 0, TD04 = 0, TD07 = 0, TD11 = 0, TD14 = 0, TD17 = 0, TD21 = 0, TD24 = 0,
                    TD27 = 0, TD28 = 0, TD29 = 0, TD30 = 0, TD31 = 0, TD32 = 0, TD34 = 0, TD37 = 0,
                    TD41 = 0, TD42 = 0, TD44 = 0, TD47 = 0, TD51 = 0, TD54 = 0;
            string Machine_flag11 = "0", Machine_flag21 = "0", Machine_flag32 = "0", Machine_flag30 = "0";
            StringBuilder sbFilterPartNo = new StringBuilder();
            StringBuilder sbFilterPartNoSJ = new StringBuilder();
         
            sbFilterPartNoSJ.AppendFormat(@" and PartNo IN ('{0}')", string.Join("','", listP.ToArray()));
            sbFilterPartNo.AppendFormat(@" and A.PartNumber IN ('{0}')", string.Join("','", listP.ToArray()));
            DataTable dtall = gd.GetSJSql(sbFilterPartNo.ToString());//获取所有SJ部件号数据 
            DataTable SJR = gOperate.GetSJR_DATA(sbFilterPartNoSJ.ToString());//获取SJ导入数据
            //判断是否有不存在的数据
            if (dtall.Rows.Count <= 0)
            {
                foreach (var item in listP)
                {
                    SaveError(item, SJR.Select("PartNo='" + item + "'")[0].ItemArray[1].ToString(), "特征表数据不存在");
                    errorList.Add(item);
                    
                }
                return;
            }
            for (int i = 0; i < dtall.Rows.Count; i++)
            {
                LS1.Add(dtall.Rows[i]["PartNumber"].ToString());
            }
            IEnumerable<string> exceptLs = listP.Except(LS1);//差集
            foreach (var item1 in exceptLs)
            {
                failNull++;
                SaveError(item1, SJR.Select("PartNo='" + item1 + "'")[0].ItemArray[1].ToString(), "特征表数据不存在");
                errorList.Add(item1);               
            }

            DataTable dtOperational = gOperate.GetOperationSql(DateTime.Now.ToString("yyyy-MM-dd"));//获取工序动作对应的单位工时--增加生效时间
            DataTable dtFactor = gOperate.GetFactor(DateTime.Now.ToString("yyyy-MM-dd"));//获取宽放系数--增加生效时间
            // DataTable dtMachine = gOperate.GetMachineData(cbeMachineVer.Text);//获取机器数据
            DataTable dtNew = dt.GetTable_SJ();//定义-动态生成输出表
            DataRow dr = dtNew.NewRow();//定义-动态生成输出行
            DataTable dtRouting = c_routing.GetTable_Routing();//工艺路线流水号输出表
            DataRow drRouting = dtRouting.NewRow();//路线代码组输出表
            DataTable dtSerial = gOperate.GetRouting();
            DataRow drser = dtSerial.Select("1=1", "IDNO ASC").LastOrDefault();//主表最后一行数据
            //特殊处理 之前把不是44组别的也查出来，往后累计，导致组别异常，但是出现异常的组别不能重新增加，需要保留，后续新的才新增
            DataTable dtSerialTemp = gOperate.GetRouting_Temp();
            if (dtall.Rows.Count > 0)
            {
                for (int j = 0; j < dtall.Rows.Count; j++)
                {
                    string[] ListRouting = dtall.Rows[j]["routing"].ToString().Split('-');//得到图纸的工艺路线
                    #region 插入行
                    dr = dtNew.NewRow();
                    dr["PartNumber"] = dtall.Rows[j]["PartNumber"].ToString();//部件号
                    dr["DrawNum"] = dtall.Rows[j]["Drawing_Num"].ToString();//图纸号
                    dr["Width_1"] = dtall.Rows[j]["Width_1"].ToString();//W1
                    dr["Dedth_1"] = dtall.Rows[j]["Depth_1"].ToString();//D1
                    dr["Width_2"] = dtall.Rows[j]["Width_2"].ToString();//W2
                    dr["Dedth_2"] = dtall.Rows[j]["Depth_2"].ToString();//D2
                    dr["Tinckness"] = dtall.Rows[j]["Thickness"].ToString();//厚度
                    dr["D_Cutting_Size"] = dtall.Rows[j]["D_Cutting_Size"].ToString();//切割尺寸
                    dr["WorkCenterNumber"] = dtall.Rows[j]["routing"].ToString();//工艺路线
                    dr["Decription"] = dtall.Rows[j]["Description"].ToString();//部件描述
                    dr["Cycle"] = 0;//周期
                    dr["CreateDate"] = DateTime.Now;
                    dr["Flag"] = "2";

                    #endregion

                    foreach (var item in ListRouting)
                    {
                        switch (item.ToString())
                        {
                            case "D01":
                                TD01 = 16;
                                dr["D01"] = TD01;
                                RoutingList.Add(TD01);
                                break;
                            case "D04":
                                TD04 = Math.Ceiling(c_d04.GetD04(dtall.Rows[j]["Width_1"].ToString(), dtall.Rows[j]["Width_2"].ToString())
                                    * (dtFactor.Select("PROCESS_CODE='D04'").Length <= 0 ? 1 :
                                     1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D04'"))[0].ItemArray[1].ToString())));
                                dr["D04"] = TD04;
                                RoutingList.Add(TD04);
                                if (TD04 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                        SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                        ,item.ToString() + "的工时为0");
                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D07":
                                TD07 = Math.Ceiling(c_d07.GetD07(dtall.Rows[j]["Width_1"].ToString(), dtall.Rows[j]["Width_2"].ToString())
                                     * (dtFactor.Select("PROCESS_CODE='D07'").Length <= 0 ? 1 :
                                    1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D07'"))[0].ItemArray[1].ToString())));
                                dr["D07"] = TD07;
                                RoutingList.Add(TD07);
                                if (TD07 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                       SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                       , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D11":
                                double[] ArrayTD11 = c_d11.GetD11(dtall.Select("Drawing_Num='" + dtall.Rows[j]["Drawing_Num"].ToString() + "' and PartNumber='" + dtall.Rows[j]["PartNumber"].ToString() + "'"),
                                   dtOperational.Select("WORKSTATION_LIST like '%D11%'"),
                                    // dtMachine.Select("Part_No='" + dtall.Rows[j]["PartNumber"].ToString() + "' and Machine_Name='D11'"));
                                 null);//机器时间
                                TD11 = ArrayTD11[0];
                                Machine_flag11 = ArrayTD11[1].ToString() == "1" ? "PH" : "0";

                                dr["D11"] = Math.Ceiling(TD11 * (dtFactor.Select("PROCESS_CODE='D11'").Length <= 0 ? 1 :
                                   1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D11'"))[0].ItemArray[1].ToString())));
                                RoutingList.Add(Convert.ToDouble(dr["D11"]));
                                if (TD11 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                       SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                       , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D14":
                                TD14 = Math.Ceiling(c_d14.GetD14(dtall.Rows[j]["Width_1"].ToString(), dtall.Rows[j]["Width_2"].ToString())
                                     * (dtFactor.Select("PROCESS_CODE='D14'").Length <= 0 ? 1 :
                                    1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D14'"))[0].ItemArray[1].ToString())));
                                dr["D14"] = Math.Ceiling(TD14);
                                RoutingList.Add(TD14);
                                if (TD14 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                       SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                       , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D17":
                                TD17 = 24;
                                dr["D17"] = TD17;
                                RoutingList.Add(TD17);
                                break;
                            case "D21":
                                double[] ArrayTD21 = c_d21.GetD21(dtall.Select("Drawing_Num='" + dtall.Rows[j]["Drawing_Num"].ToString() + "' and PartNumber='" + dtall.Rows[j]["PartNumber"].ToString() + "'"),
                                  dtOperational.Select("WORKSTATION_LIST like '%D21%'"),
                                  dtall.Rows[j]["D21_Component_Type"].ToString(),
                                    //dtMachine.Select("Part_No='" + dtall.Rows[j]["PartNumber"].ToString() + "' and Machine_Name='D21'"));
                                 null);//机器时间
                                TD21 = ArrayTD21[0];
                                Machine_flag21 = ArrayTD21[1].ToString() == "1" ? "BIMA" : "0";

                                dr["D21"] = Math.Ceiling(TD21 * (dtFactor.Select("PROCESS_CODE='D21'").Length <= 0 ? 1 :
                                    1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D21'"))[0].ItemArray[1].ToString())));
                                RoutingList.Add(Convert.ToDouble(dr["D21"]));
                                if (TD21 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                      SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                      , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D24":
                                TD24 = Math.Ceiling(c_d24.GetD24(dtall.Select("Drawing_Num='" + dtall.Rows[j]["Drawing_Num"].ToString() + "' and PartNumber='" + dtall.Rows[j]["PartNumber"].ToString() + "'"),
                                    dtOperational.Select("WORKSTATION_LIST like '%D24%'"))
                                     * (dtFactor.Select("PROCESS_CODE='D24'").Length <= 0 ? 1 :
                                    1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D24'"))[0].ItemArray[1].ToString())));
                                dr["D24"] = TD24;
                                RoutingList.Add(TD24);
                                if (TD24 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                      SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                      , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D27":
                                TD27 = Math.Ceiling(c_d27.GetD27(dtall.Select("Drawing_Num='" + dtall.Rows[j]["Drawing_Num"].ToString() + "' and PartNumber='" + dtall.Rows[j]["PartNumber"].ToString() + "'"),
                                    dtOperational.Select("WORKSTATION_LIST like '%D27%'"))
                                    * (dtFactor.Select("PROCESS_CODE='D27'").Length <= 0 ? 1 :
                                    1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D27'"))[0].ItemArray[1].ToString())));
                                dr["D27"] = TD27;
                                RoutingList.Add(TD27);
                                if (TD27 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                       SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                       , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D28":
                                TD28 = Math.Ceiling(c_d28.GetD28(dtall.Rows[j]["Width_1"].ToString(), dtall.Rows[j]["Width_2"].ToString(), dtall.Rows[j]["D28_Sealing_Diagonal_Edge"].ToString())
                                     * (dtFactor.Select("PROCESS_CODE='D28'").Length <= 0 ? 1 :
                                    1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D28'"))[0].ItemArray[1].ToString())));
                                dr["D28"] = TD28;
                                RoutingList.Add(TD28);
                                if (TD28 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                      SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                      , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D29":
                                TD29 = Math.Ceiling(c_d29.GetD29(dtall.Rows[j]["Width_1"].ToString(), dtall.Rows[j]["Width_2"].ToString(), dtall.Rows[j]["D29_Seal_Straight_Line_Edge"].ToString())
                                     * (dtFactor.Select("PROCESS_CODE='D29'").Length <= 0 ? 1 :
                                    1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D29'"))[0].ItemArray[1].ToString())));
                                dr["D29"] = TD29;
                                RoutingList.Add(TD29);
                                if (TD29 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                       SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                       , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D30":
                                double[] ArrayTD30 = c_d30.GetD30(dtall.Select("Drawing_Num='" + dtall.Rows[j]["Drawing_Num"].ToString() + "' and PartNumber='" + dtall.Rows[j]["PartNumber"].ToString() + "'"),
                                    dtOperational.Select("WORKSTATION_LIST like '%D30%'"),
                                    //Convert.ToDouble(gOperate.GetMachineData("D11", dtall.Rows[j]["PartNumber"].ToString()).Rows[0][0].ToString())
                                   0);//机器时间
                                TD30 = ArrayTD30[0];
                                Machine_flag30 = ArrayTD30[1].ToString();
                                dr["D30"] = Math.Ceiling(TD30 * (dtFactor.Select("PROCESS_CODE='D30'").Length <= 0 ? 1 :
                                   1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D30'"))[0].ItemArray[1].ToString())));
                                RoutingList.Add(Convert.ToDouble(dr["D30"]));
                                if (TD30 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                      SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                      , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D31":
                                TD31 = Math.Ceiling(c_d31.GetD31(dtall.Rows[j]["Width_1"].ToString(), dtall.Rows[j]["Width_2"].ToString(), dtall.Rows[j]["D31_Seal_Straight_Line_Edge"].ToString())
                                     * (dtFactor.Select("PROCESS_CODE='D31'").Length <= 0 ? 1 :
                                    1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D31'"))[0].ItemArray[1].ToString())));
                                dr["D31"] = TD31;
                                RoutingList.Add(TD31);
                                if (TD31 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                       SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                       , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D32":
                                double[] ArrayTD32 = c_d32.GetD32(dtall.Select("Drawing_Num='" + dtall.Rows[j]["Drawing_Num"].ToString() + "' and PartNumber='" + dtall.Rows[j]["PartNumber"].ToString() + "'"),
                                   dtOperational.Select("WORKSTATION_LIST like '%D32%'"),
                                   dtall.Rows[j]["D32_Component_Type"].ToString(),
                                    //  Convert.ToDouble(gOperate.GetMachineData("D32", dtall.Rows[j]["PartNumber"].ToString()).Rows[0][0].ToString())//机器时间
                                0);//暂时取0
                                TD32 = ArrayTD32[0] * 1.5;
                                Machine_flag32 = ArrayTD32[1].ToString();

                                dr["D32"] = Math.Ceiling(TD32 * (dtFactor.Select("PROCESS_CODE='D32'").Length <= 0 ? 1 :
                                1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D32'"))[0].ItemArray[1].ToString())));
                                RoutingList.Add(Convert.ToDouble(dr["D32"]));
                                if (TD32 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                       SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                       , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D34":
                                TD34 = Math.Ceiling(c_d34.GetD34(dtall.Select("Drawing_Num='" + dtall.Rows[j]["Drawing_Num"].ToString() + "' and PartNumber='" + dtall.Rows[j]["PartNumber"].ToString() + "'"),
                                    dtOperational.Select("WORKSTATION_LIST like '%D34%'"),
                                    dtall.Rows[j]["D34_Component_Type"].ToString(),
                                    dtall.Rows[j]["D34_Edge_Thickness"].ToString())
                                     * (dtFactor.Select("PROCESS_CODE='D34'").Length <= 0 ? 1 :
                                     1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D34'"))[0].ItemArray[1].ToString())));
                                dr["D34"] = TD34;
                                RoutingList.Add(TD34);
                                if (TD34 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                       SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                       , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D37":
                                TD37 = Math.Ceiling((c_d37.GetD37(dtall.Select("Drawing_Num='" + dtall.Rows[j]["Drawing_Num"].ToString() + "' and PartNumber='" + dtall.Rows[j]["PartNumber"].ToString() + "'"),
                                    dtOperational.Select("WORKSTATION_LIST like '%D37%'"), dtall.Rows[j]["routing"].ToString()))
                                     * (dtFactor.Select("PROCESS_CODE='D37'").Length <= 0 ? 1 :
                                     1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D37'"))[0].ItemArray[1].ToString())));
                                dr["D37"] = TD37;
                                RoutingList.Add(TD37);
                                if (TD37 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                      SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                      , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D41":
                                TD41 = Math.Ceiling(c_d41.GetD41(dtall.Select("Drawing_Num='" + dtall.Rows[j]["Drawing_Num"].ToString() + "' and PartNumber='" + dtall.Rows[j]["PartNumber"].ToString() + "'"),
                                    dtOperational.Select("WORKSTATION_LIST like '%D41%'"), dtall.Rows[j]["routing"].ToString())
                                     * (dtFactor.Select("PROCESS_CODE='D41'").Length <= 0 ? 1 :
                                    1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D41'"))[0].ItemArray[1].ToString())));
                                dr["D41"] = TD41;
                                RoutingList.Add(TD41);
                                if (TD41 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                       SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                       , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                            case "D42":
                                TD42 = Math.Ceiling(c_d42.GetD42(dtall.Rows[j]["Width_1"].ToString(),
                                    dtall.Rows[j]["Width_2"].ToString(),
                                     dtall.Rows[j]["GROUP_CODE"].ToString()));
                                dr["D42"] = TD42;
                                RoutingList.Add(TD42);
                                if (TD42 == 0)
                                {
                                    SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                      SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                      , item.ToString() + "的工时为0");

                                    errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                                    continue;
                                }
                                break;
                        }
                    }
                    //if (fail > failNull || fail > 0)
                    //    continue;
                    if (errorList.Contains(dtall.Rows[j]["PartNumber"].ToString()))
                        continue;
                    
                    #region 工艺代码组赋值
                    if (RoutingList.Count == 0)
                    {
                        SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                      SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                      , "所有工序工时为0");

                        errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                        continue;
                    }
                    if (string.IsNullOrEmpty(dtall.Rows[j]["GROUP_CODE"].ToString()))
                    {
                        SaveError(dtall.Rows[j]["PartNumber"].ToString(),
                                      SJR.Select("PartNo='" + dtall.Rows[j]["PartNumber"].ToString() + "'")[0].ItemArray[1].ToString()
                                      , "无工艺路线简码");

                        errorList.Add(dtall.Rows[j]["PartNumber"].ToString());
                        continue;
                    }
                    foreach (var list in RoutingList)
                    {
                        Routing_dec += list + "_";
                    }
                    dr["CountDecription"] = dtall.Rows[j]["GROUP_CODE"].ToString() + "_" + Routing_dec.Substring(0, Routing_dec.Length - 1);//代码组描述

                    DataRow drTemp = dtRouting.Select("1=1", "Serial ASC").LastOrDefault();//临时表最后一行数据
                    drRouting = dtRouting.NewRow();//路线代码组输出表   
                    DataRow[] drTemp2 = dtSerial.Select("Calculate_Desc='" + dr["CountDecription"] + "'");//主表
                    DataRow[] drTemp1 = dtRouting.Select("Calculate_Desc='" + dr["CountDecription"] + "'");//临时表
                    DataRow[] drTemp3 = dtSerialTemp.Select("Calculate_Desc='" + dr["CountDecription"] + "'");//主表-特殊计算 后续可删除
                    if (drTemp3.Length > 0)
                    {
                        dr["GROUP_CODE"] = drTemp3[0]["Routing_Group"];
                        dr["iCount"] = drTemp3[0]["Calculate"];
                    }
                    else if (drTemp2.Length > 0)
                    {
                        dr["GROUP_CODE"] = drTemp2[0]["Routing_Group"];
                        dr["iCount"] = drTemp2[0]["Calculate"];
                    }                 
                    else
                    {
                        if (drTemp1.Length > 0)
                        {

                            dr["GROUP_CODE"] = drTemp1[0]["Routing_Group"];
                            dr["iCount"] = drTemp1[0]["Calculate"];

                        }
                        else
                        {
                            if (first)
                            {
                                Serial = 1;
                                if (drser != null)
                                {
                                    if (Convert.ToInt32(drser["Calculate"]) >= 2 && Convert.ToInt32(drser["Calculate"]) < 99)
                                    {
                                        drRouting["Routing_Group"] = Convert.ToInt32(drser["Routing_Group"]);
                                        drRouting["Calculate"] = Convert.ToInt32(drser["Calculate"]) + 1;

                                    }
                                    else if (Convert.ToInt32(drser["Calculate"]) == 99)
                                    {
                                        drRouting["Routing_Group"] = Convert.ToInt32(drser["Routing_Group"]) + 1;
                                        drRouting["Calculate"] = 2;
                                    }
                                }
                                else
                                {
                                    drRouting["Routing_Group"] = 44000001;
                                    drRouting["Calculate"] = 2;
                                }
                                dr["GROUP_CODE"] = drRouting["Routing_Group"];
                                dr["iCount"] = drRouting["Calculate"];
                                Routing_Group = Convert.ToInt32(drRouting["Routing_Group"]);
                                Calculate = Convert.ToInt32(drRouting["Calculate"]);
                            }
                            else
                            {
                                Serial = Convert.ToInt32(drTemp["Serial"]) + 1;
                                if (drTemp != null)
                                {
                                    if (Convert.ToInt32(drTemp["Calculate"]) >= 2 && Convert.ToInt32(drTemp["Calculate"]) < 99)
                                    {
                                        drRouting["Routing_Group"] = Convert.ToInt32(drTemp["Routing_Group"]);
                                        drRouting["Calculate"] = Convert.ToInt32(drTemp["Calculate"]) + 1;

                                    }
                                    else if (Convert.ToInt32(drTemp["Calculate"]) == 99)
                                    {
                                        drRouting["Routing_Group"] = Convert.ToInt32(drTemp["Routing_Group"]) + 1;
                                        drRouting["Calculate"] = 2;
                                    }
                                }
                                else
                                {
                                    drRouting["Routing_Group"] = 44000001;
                                    drRouting["Calculate"] = 2;
                                }
                                dr["GROUP_CODE"] = drRouting["Routing_Group"];
                                dr["iCount"] = drRouting["Calculate"];
                                Routing_Group = Convert.ToInt32(drRouting["Routing_Group"]);
                                Calculate = Convert.ToInt32(drRouting["Calculate"]);
                            }
                            //}
                            //存在的数据不需要插入到数据库
                            // drRouting = dtRouting.NewRow();//路线代码组输出表                     
                            drRouting["Serial"] = Serial;
                            drRouting["Routing_Group"] = Routing_Group;
                            drRouting["Calculate"] = Calculate;
                            drRouting["Calculate_Desc"] = dr["CountDecription"];
                            drRouting["Date_TS"] = DateTime.Now;
                            drRouting["Update_User"] = Lamex.Common.Loginer.CurrentUser.AccountName;
                            dtRouting.Rows.Add(drRouting);
                            first = false;
                        }
                    }
                    #endregion
                    // dr["Machine_Flag"] = Machine_flag11 + "," + Machine_flag21 + "," + Machine_flag32;
                    dtNew.Rows.Add(dr);
                    #region 插入临时表后数据全部初始化为0
                    TD01 = 0;
                    TD04 = 0;
                    TD07 = 0;
                    TD11 = 0;
                    TD14 = 0;
                    TD17 = 0;
                    TD21 = 0;
                    TD24 = 0;
                    TD27 = 0;
                    TD28 = 0;
                    TD29 = 0;
                    TD30 = 0;
                    TD31 = 0;
                    TD32 = 0;
                    TD34 = 0;
                    TD37 = 0;
                    TD41 = 0;
                    TD42 = 0;
                    TD44 = 0;
                    TD47 = 0;
                    TD51 = 0;
                    TD54 = 0;
                    Machine_flag11 = "0";
                    Machine_flag21 = "0";
                    Machine_flag32 = "0";
                    Machine_flag30 = "0";
                    RoutingList = new List<double>();
                    Routing_dec = "";
                    Serial = 0;
                    Routing_Group = 0;
                    Calculate = 0;
                    #endregion
                    sucess++;
                }
            }

            //工艺路线流水号批量插入主表-B_IE_Calculator_Routing
            if (BaseBuildSql.ExcuteInsert(dtRouting, "B_IE_Calculator_Routing"))
            {

                dtRouting = new DataTable();
            }
            //工时保存--重复的删除
            //DataTable dtDelete = c_Bom.DataTableContrast_TIME(dtWork_Time, dtNew);
            StringBuilder sbFilter = new StringBuilder();
            StringBuilder sbFilterSJ = new StringBuilder();
            StringBuilder sbFilterST = new StringBuilder();
            List<string> delete = new List<string>();
            if (dtNew.Rows.Count > 0)
            {
                for (int i = 0; i < dtNew.Rows.Count; i++)
                {
                    delete.Add(dtNew.Rows[i][0].ToString());
                }
                sbFilter.AppendFormat(@"  PartNumber IN ('{0}')", string.Join("','", delete.ToArray()));
                sbFilterSJ.AppendFormat(@"  PartNo IN ('{0}')", string.Join("','", delete.ToArray()));
                sbFilterST.AppendFormat(@"  DRAWING_NUMBER IN ('{0}')", string.Join("','", delete.ToArray()));
                string sqlDel = @"Delete  FROM [LamexMESManager].[dbo].[B_IE_WorkTimeHistory] where " + sbFilter + "";
                int n = BaseBuildSql.ExecuteNonQuery(sqlDel);
                //插入表后更新标识
                string updateSql1 = @"update [LamexMESManager].[dbo].[B_IE_SJR_DATA] set Calculate_Flag=1,Calculate_TS=GETDATE() where " + sbFilterSJ + "";
                string updateSql2 = @"update [LamexMESManager].[dbo].[B_IE_Operation_Data] set FLAG='2' where " + sbFilterST + "";
                int m = BaseBuildSql.ExecuteNonQuery(updateSql1 + updateSql2);
            }

            if (BaseBuildSql.ExcuteInsert(dtNew, "B_IE_WorkTimeHistory"))
            {

            }
            // sumCount = dtall.Rows.Count > 0 ? dtall.Rows.Count : 0;//总行数
            dtNew = new DataTable();
            #endregion
        }
        //清空图片控件值
        public void ClearPic()
        {
            #region 清空控件值
            int tabCount5 = this.xtraTabControl5.TabPages.Count;
            int tabCount4 = this.xtraTabControl4.TabPages.Count;
            for (int i = tabCount4 - 1; i >= 0; i--)
            {

                this.xtraTabControl4.TabPages.RemoveAt(i);

            }
            for (int i = tabCount5 - 1; i >= 0; i--)
            {

                this.xtraTabControl5.TabPages.RemoveAt(i);

            }
            Page = new XtraTabPage();
            pic = new PictureBox();
            TabPageDic = new Dictionary<string, XtraTabPage>();
            TabPageDicSJ = new Dictionary<string, XtraTabPage>();
            PictureDic = new Dictionary<string, PictureBox>();
            PictureDicSJ = new Dictionary<string, PictureBox>();
            BitDic = new Dictionary<string, Bitmap>();
            BitDicSJ = new Dictionary<string, Bitmap>();
            #endregion
        }
        private void txtEditDRAWING_NUMBER_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                Search();
            }

        }
        private void Search()
        {
            foreach (Control c in panelControl9.Controls)
            {
                if (c is TextEdit)
                {
                    TextEdit t = c as TextEdit;
                    if (c.Name != "txtEditDRAWING_NUMBER")
                    {
                        t.Enabled = true;
                        t.BackColor = Color.White;
                        t.Properties.ReadOnly = false;
                        t.Text = "";


                    }
                }
            }
            #region 根据图纸号查询
            string sqlBZ = @"SELECT 
              Drawing_No
              FROM [LamexMESManager].[dbo].[B_IE_SJR_DATA] where [PartNo]='" + txtEditDRAWING_NUMBER.Text + "'";

            //            string sql = @"SELECT * from [Edgeband_Program].[dbo].[Initial_Data]  where 
            //Drawing_Num collate Chinese_PRC_CI_AS in (select [DRAWING_NO_STANDARD] from  [LamexMESManager].[dbo].[B_IE_SJData_Import] 
            //where DRAWING_NO_SJ='" + txtEditDRAWING_NUMBER.Text + "') ";
            string sql = @"  SELECT PART_NUMBER,
  WORKCENTER_NUMBER +'_'+WORKCENTER_DESCRIPTION as 'Procedure'   
  FROM [Edgeband_Program].[dbo].[ROUTING_TEMP_DATA]
  where PART_NUMBER='" + txtEditDRAWING_NUMBER.Text + "' ORDER BY PROCESS_STEP";
            if (string.IsNullOrEmpty(txtEditDRAWING_NUMBER.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请输入图纸编号", "提示", MessageBoxButtons.OK);
                return;
            }
            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);//获取标准图号信息
            DataTable dtBZ = BaseBuildSql.GetDataTableBySql(sqlBZ);//获取标准图号
            if (dt.Rows.Count > 0)
            {
                //取一行即可
                //txtEditNUMBER1.Text = dt.Rows[0]["Procedure_01"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_01"].ToString();
                //txtEditNUMBER2.Text = dt.Rows[0]["Procedure_02"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_02"].ToString();
                //txtEditNUMBER3.Text = dt.Rows[0]["Procedure_03"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_03"].ToString();
                //txtEditNUMBER4.Text = dt.Rows[0]["Procedure_04"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_04"].ToString();
                //txtEditNUMBER5.Text = dt.Rows[0]["Procedure_05"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_05"].ToString();
                //txtEditNUMBER6.Text = dt.Rows[0]["Procedure_06"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_06"].ToString();
                //txtEditNUMBER7.Text = dt.Rows[0]["Procedure_07"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_07"].ToString();
                //txtEditNUMBER8.Text = dt.Rows[0]["Procedure_08"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_08"].ToString();
                //txtEditNUMBER9.Text = dt.Rows[0]["Procedure_09"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_09"].ToString();
                //txtEditNUMBER10.Text = dt.Rows[0]["Procedure_10"].ToString() == "x" ? "" : dt.Rows[0]["Procedure_10"].ToString();
                foreach (Control c in panelControl9.Controls)
                {
                    if (c is TextEdit)
                    {
                        //c.Name为随机控件值，不是按顺利排列的                       
                        if (c.Name != "txtEditDRAWING_NUMBER")
                        {
                            //使用正则表达式获取数字
                            int result = Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(c.Name, @"[^0-9]+", ""));
                            if (result <= dt.Rows.Count)
                            {
                                c.Text = dt.Rows[result - 1]["Procedure"].ToString();
                            }

                        }
                    }
                }

            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("该图纸号不存在", "提示", MessageBoxButtons.OK);
                ReFresh();
                return;
            }
            #endregion
            #region 加载图片
            #region 清空控件值
            int tabCount2 = this.xtraTabControl2.TabPages.Count;
            int tabCount3 = this.xtraTabControl3.TabPages.Count;
            for (int i = tabCount2 - 1; i >= 0; i--)
            {

                this.xtraTabControl2.TabPages.RemoveAt(i);

            }
            for (int i = tabCount3 - 1; i >= 0; i--)
            {

                this.xtraTabControl3.TabPages.RemoveAt(i);

            }
            Page = new XtraTabPage();
            pic = new PictureBox();
            TabPageDic = new Dictionary<string, XtraTabPage>();
            TabPageDicSJ = new Dictionary<string, XtraTabPage>();
            PictureDic = new Dictionary<string, PictureBox>();
            PictureDicSJ = new Dictionary<string, PictureBox>();
            BitDic = new Dictionary<string, Bitmap>();
            BitDicSJ = new Dictionary<string, Bitmap>();
            #endregion
            int Num = 0, NumSJ = 0;
            int Count = 0;
            string pictureName = "";//标准图号
            if (dtBZ.Rows.Count > 0)
                pictureName = dtBZ.Rows[0][0].ToString();
            string pictureNameSJ = txtEditDRAWING_NUMBER.Text;//SJ图纸号
            List<string> pictureNames = new List<string>();
            List<string> pictureNamesSJ = new List<string>();
            string filename = "", filenameSJ = "";// @"R:\SJ\STD_DESK_DWG\SUMMARY\";
            #region XML配置图片路径
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath + "\\PicturePathConfig.xml");
            XmlNode xn = doc.SelectSingleNode("Pictures");
            XmlNodeList xnl = xn.ChildNodes;
            foreach (XmlNode xn1 in xnl)
            {
                XmlElement xe = (XmlElement)xn1;
                XmlNodeList xn2 = xe.ChildNodes;
                filename = xn2.Item(0).InnerText;//读取标准图片路径
                Count = Convert.ToInt32(xn2.Item(1).InnerText);//读取最大图片张数
                filenameSJ = xn2.Item(2).InnerText;//读取SJ图片路径
            }
            //定位到标准具体图纸（默认10张，可以通过xml配置）
            for (int i = 0; i < Count; i++)
            {
                string picTemp = "";//定义每张标准图片路径
                if (i == 0)
                {
                    picTemp = filename + pictureName + ".tif";//标准图片只存在一张的情况
                }
                else
                {
                    picTemp = filename + pictureName + "-" + i + ".tif";////标准图片存在多张的情况
                }
                if (!File.Exists(picTemp))
                {
                    continue;
                }
                pictureNames.Add(picTemp);
                Num++;
            }
            //定位到SJ具体图纸（默认10张，可以通过xml配置）
            for (int i = 0; i < Count; i++)
            {
                string picTempSJ = "";//定义每张SJ图片路径
                if (i == 0)
                {
                    picTempSJ = filenameSJ + pictureNameSJ + ".tif";//SJ图片只存在一张的情况
                }
                else
                {
                    picTempSJ = filenameSJ + pictureNameSJ + "-" + i + ".tif";//SJ图片存在多张的情况
                }
                if (!File.Exists(picTempSJ))
                {
                    continue;
                }
                pictureNamesSJ.Add(picTempSJ);
                NumSJ++;
            }

            #endregion

            for (int i = 0; i < Num; i++)
            {

                AddTabpage(xtraTabControl2, "xtrPage" + (i + 1), "第" + (i + 1) + "张", "pictureBox" + (i + 1), pictureNames[i].ToString());

            }
            for (int i = 0; i < NumSJ; i++)
            {

                AddTabpageSJ(xtraTabControl3, "xtrPage" + (i + 1), "第" + (i + 1) + "张", "pictureBox" + (i + 1), pictureNamesSJ[i].ToString());

            }
            xtraTabControl2.SelectedTabPageIndex = 0;//默认选中第一页
            xtraTabControl3.SelectedTabPageIndex = 0;//默认选中第一页
            #endregion
            #region 加载动作定义列表
            foreach (Control c in panelControl9.Controls)
            {
                if (c is TextEdit)
                {
                    if (c.Name != "txtEditDRAWING_NUMBER")
                    {

                        if (string.IsNullOrEmpty(c.Text))
                        {
                            TextEdit t = c as TextEdit;
                            t.Enabled = false;
                            t.Properties.ReadOnly = true;
                            t.BackColor = Color.LightGray;

                        }

                    }
                }
            }
            ucAutoAddControls1.Claer();
            ucAutoAddControls1.DrawingNumber = txtEditDRAWING_NUMBER.Text;
            ucAutoAddControls1.userName = Lamex.Common.Loginer.CurrentUser.Account;
            foreach (Control c in panelControl9.Controls)
            {
                if (c is TextEdit)
                {
                    if ("txtEditDRAWING_NUMBER" != c.Name)
                    {
                        string[] strArr = c.Text.Split('_');
                        if (strArr.Count() > 0)
                        {
                            editControl = c as TextEdit;
                            workProcess = strArr[0];
                            if (!string.IsNullOrEmpty(workProcess))
                                //ucAutoAddControls1.LoadListImtes(strArr[0], editControl, txtEditDRAWING_NUMBER.Text);
                                ucAutoAddControls1.LoadDataType(txtEditDRAWING_NUMBER.Text, Lamex.Common.Loginer.CurrentUser.Account, DateTime.Now.ToString(), workProcess, editControl);
                        }
                    }

                }

            }
            #endregion
            #region 根据标准图号插入数据到临时表
            ucAutoAddControls1.SaveTempSJ(pictureNameSJ, pictureName);
            #endregion
            string sql2 = @"update B_IE_SJR_DATA set LockMan='" + Lamex.Common.Loginer.CurrentUser.Account + "',Locked=1 where PartNo='" + txtEditDRAWING_NUMBER.Text + "'";
            BaseFactory<B_IE_SJData_Import>.Instance.ExecuteNonQuery(sql2);

        }
        private void uceditKeyPress_UcTextKeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!string.IsNullOrEmpty(uceditKeyPress.Text))
                {
                    if (gridView2.RowCount < 0) return;
                    for (int i = 0; i < gridView2.RowCount; i++)
                    {
                        if (uceditKeyPress.Text.Trim() == gridView2.GetRowCellDisplayText(i, "PartNo").ToString())
                        {
                            gridView2.FocusedRowHandle = i;
                            //gridView2.SelectRow(i);
                            gcViewAll_Click(null, null);
                        }

                    }


                }
                else
                {
                    InitializeForm();
                }
            }


        }            
        private void gcViewAll_Click(object sender, EventArgs e)
        {
            if (gridView2.RowCount < 0) return;          
            int iRow = gridView2.FocusedRowHandle;
            string strDrawingNo = gridView2.GetRowCellDisplayText(iRow, "PartNo").ToString();
         
            //控制锁定录入员
            string sql1 = @"select * from  [LamexMESManager].[dbo].[B_IE_SJR_DATA]  where PartNo='" + strDrawingNo + "' and Locked=1 ";
            string sql3 = @"select * from  [LamexMESManager].[dbo].[B_IE_SJR_DATA]  where PartNo='" + strDrawingNo + "' and Locked=1 and LockMan='" + Lamex.Common.Loginer.CurrentUser.Account + "'";
            DataTable dt1 = BaseFactory<B_IE_SJData_Import>.Instance.GetDataTableBySql(sql1);
            DataTable dt2 = BaseFactory<B_IE_SJData_Import>.Instance.GetDataTableBySql(sql3);

            if (dt1.Rows.Count > 0 && dt2.Rows.Count == 0)
            {
                string name = dt1.Rows[0]["LockMan"].ToString();
                XtraMessageBox.Show("录入员-" + name + "：正在操作此图纸号");
                return;
            }
            //自动勾选
            gridView2.SelectRow(iRow);
            //点击即锁定
            string sql2 = @"update B_IE_SJR_DATA set LockMan='" + Lamex.Common.Loginer.CurrentUser.Account + "',Locked=1 where PartNo='" + strDrawingNo + "'";
            BaseFactory<B_IE_SJData_Import>.Instance.ExecuteNonQuery(sql2);                 

            string sqlBZ = @"SELECT 
              Drawing_No
              FROM [LamexMESManager].[dbo].[B_IE_SJR_DATA] where [PartNo]='" + strDrawingNo + "'";


            string sql = @"  SELECT PART_NUMBER,
              WORKCENTER_NUMBER +'_'+WORKCENTER_DESCRIPTION as 'Procedure'   
              FROM [Edgeband_Program].[dbo].[ROUTING_TEMP_DATA]
              where PART_NUMBER='" + strDrawingNo + "'";

            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);//获取标准图号信息
            DataTable dtBZ = BaseBuildSql.GetDataTableBySql(sqlBZ);//获取标准图号

            #region 加载图片
            #region 清空控件值
            int tabCount5 = this.xtraTabControl5.TabPages.Count;
            int tabCount4 = this.xtraTabControl4.TabPages.Count;
            for (int i = tabCount4 - 1; i >= 0; i--)
            {

                this.xtraTabControl4.TabPages.RemoveAt(i);

            }
            for (int i = tabCount5 - 1; i >= 0; i--)
            {

                this.xtraTabControl5.TabPages.RemoveAt(i);

            }
            Page = new XtraTabPage();
            pic = new PictureBox();
            TabPageDic = new Dictionary<string, XtraTabPage>();
            TabPageDicSJ = new Dictionary<string, XtraTabPage>();
            PictureDic = new Dictionary<string, PictureBox>();
            PictureDicSJ = new Dictionary<string, PictureBox>();
            BitDic = new Dictionary<string, Bitmap>();
            BitDicSJ = new Dictionary<string, Bitmap>();
            #endregion
            int Num = 0, NumSJ = 0;
            int Count = 0;
            string pictureName = "";//标准图号
            if (dtBZ.Rows.Count > 0)
                pictureName = dtBZ.Rows[0][0].ToString();
            string pictureNameSJ = strDrawingNo;//SJ图纸号
            List<string> pictureNames = new List<string>();
            List<string> pictureNamesSJ = new List<string>();
            string filename = "", filenameSJ = "";// @"R:\SJ\STD_DESK_DWG\SUMMARY\";
            #region XML配置图片路径
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath + "\\PicturePathConfig.xml");
            XmlNode xn = doc.SelectSingleNode("Pictures");
            XmlNodeList xnl = xn.ChildNodes;
            foreach (XmlNode xn1 in xnl)
            {
                XmlElement xe = (XmlElement)xn1;
                XmlNodeList xn2 = xe.ChildNodes;
                filename = xn2.Item(0).InnerText;//读取标准图片路径
                Count = Convert.ToInt32(xn2.Item(1).InnerText);//读取最大图片张数
                filenameSJ = xn2.Item(2).InnerText;//读取SJ图片路径
            }
            //定位到标准具体图纸（默认10张，可以通过xml配置）
            for (int i = 0; i < Count; i++)
            {
                string picTemp = "";//定义每张标准图片路径
                if (i == 0)
                {
                    picTemp = filename + pictureName + ".tif";//标准图片只存在一张的情况
                }
                else
                {
                    picTemp = filename + pictureName + "-" + i + ".tif";////标准图片存在多张的情况
                }
                if (!File.Exists(picTemp))
                {
                    continue;
                }
                pictureNames.Add(picTemp);
                Num++;
            }
            //定位到SJ具体图纸（默认10张，可以通过xml配置）
            for (int i = 0; i < Count; i++)
            {
                string picTempSJ = "";//定义每张SJ图片路径
                if (i == 0)
                {
                    picTempSJ = filenameSJ + pictureNameSJ + ".tif";//SJ图片只存在一张的情况
                }
                else
                {
                    picTempSJ = filenameSJ + pictureNameSJ + "-" + i + ".tif";//SJ图片存在多张的情况
                }
                if (!File.Exists(picTempSJ))
                {
                    continue;
                }
                pictureNamesSJ.Add(picTempSJ);
                NumSJ++;
            }

            #endregion

            for (int i = 0; i < Num; i++)
            {

                AddTabpage(xtraTabControl5, "xtrPage" + (i + 1), "第" + (i + 1) + "张", "pictureBox" + (i + 1), pictureNames[i].ToString());

            }
            for (int i = 0; i < NumSJ; i++)
            {

                AddTabpageSJ(xtraTabControl4, "xtrPage" + (i + 1), "第" + (i + 1) + "张", "pictureBox" + (i + 1), pictureNamesSJ[i].ToString());

            }
            xtraTabControl4.SelectedTabPageIndex = 0;//默认选中第一页
            xtraTabControl5.SelectedTabPageIndex = 0;//默认选中第一页
            #endregion

        }
        private void gcViewAll_DoubleClick(object sender, EventArgs e)
        {
            int iRow = gridView2.FocusedRowHandle;
            txtEditDRAWING_NUMBER.Text = gridView2.GetRowCellDisplayText(iRow, "PartNo").ToString();
            drawNum = txtEditDRAWING_NUMBER.Text;

            xtraTabPage2.PageEnabled = true;
            xtraTabPage1.PageEnabled = false;
            Search();
        }
        private void FrmBIEOperationDataSJ_FormClosing(object sender, FormClosingEventArgs e)
        {
            string sql = "";
            sql = @"update B_IE_SJR_DATA set locked=0 where locked='1' AND LockMan='" + Lamex.Common.Loginer.CurrentUser.Account + "'";
            int m = BaseBuildSql.ExecuteNonQuery(sql);
        }
        public void SaveError(string PartNo,string Drawing_No,string strError)
        {
            string InserError = @"insert into [LamexMESManager].[dbo].[B_IE_BOM_ERRORINFO] ([Mater_No],[Drawing_No],[Create_TS],[Falg],[Describes]) 
values('" + PartNo + "','" + Drawing_No + "',GETDATE(),'2','" + strError + "')";
            int t = BaseBuildSql.ExecuteNonQuery(InserError);
            fail++;
        }      
        #region 图片切换
        private void xtraTabControl2_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            XtraTabPage Page = xtraTabControl2.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDic)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    pic = PictureDic[item.Key];
                }
            }
            pic.MouseDown += new System.Windows.Forms.MouseEventHandler(pic_MouseDown);
            pic.MouseMove += new System.Windows.Forms.MouseEventHandler(pic_MouseMove);
            pic.MouseUp += new System.Windows.Forms.MouseEventHandler(pic_MouseUp);
            pic.MouseWheel += new MouseEventHandler(pic_MouseWheel);
            Page.MouseDown += new System.Windows.Forms.MouseEventHandler(Page_MouseDown);
            Page.MouseUp += new System.Windows.Forms.MouseEventHandler(Page_MouseUp);
            Page.MouseMove += new System.Windows.Forms.MouseEventHandler(Page_MouseMove);

            #region 动态生成旋转按钮
            Page = xtraTabControl2.SelectedTabPage;
            if (Page == null)
                return;

            Button btn = new Button();
            Image clo = Image.FromFile(System.Windows.Forms.Application.StartupPath + "\\image\\left.ico");
            btn.Image = clo;
            btn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            btn.BackColor = System.Drawing.Color.Transparent;
            btn.Name = "ClockwiseBtn";
            btn.Size = new Size(47, 36);
            btn.Location = new Point(5, 445);
            Page.Controls.Add(btn);
            btn.Click += new EventHandler(aBtn_Click);

            Button btn2 = new Button();
            Image ant = Image.FromFile(System.Windows.Forms.Application.StartupPath + "\\image\\right.ico");
            btn2.Image = ant;
            btn2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            btn2.BackColor = System.Drawing.Color.Transparent;
            btn2.Name = "AntiClockwiseBtn";
            btn2.Size = new System.Drawing.Size(47, 36);
            btn2.Location = new System.Drawing.Point(55, 445);
            Page.Controls.Add(btn2);
            btn2.Click += new EventHandler(aBtn2_Click);
            #endregion
        }
        private void xtraTabControl3_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            XtraTabPage Page = xtraTabControl3.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDicSJ)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    picSJ = PictureDicSJ[item.Key];
                }
            }
            picSJ.MouseDown += new System.Windows.Forms.MouseEventHandler(picSJ_MouseDown);
            picSJ.MouseMove += new System.Windows.Forms.MouseEventHandler(picSJ_MouseMove);
            picSJ.MouseUp += new System.Windows.Forms.MouseEventHandler(picSJ_MouseUp);
            picSJ.MouseWheel += new MouseEventHandler(picSJ_MouseWheel);
            Page.MouseDown += new System.Windows.Forms.MouseEventHandler(PageSJ_MouseDown);
            Page.MouseUp += new System.Windows.Forms.MouseEventHandler(PageSJ_MouseUp);
            Page.MouseMove += new System.Windows.Forms.MouseEventHandler(PageSJ_MouseMove);

            #region 动态生成旋转按钮
            Page = xtraTabControl3.SelectedTabPage;
            if (Page == null)
                return;

            Button btn = new Button();
            Image clo = Image.FromFile(System.Windows.Forms.Application.StartupPath + "\\image\\left.ico");
            btn.Image = clo;
            btn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            btn.BackColor = System.Drawing.Color.Transparent;
            btn.Name = "ClockwiseBtnSJ";
            btn.Size = new Size(47, 36);
            btn.Location = new Point(5, 445);
            Page.Controls.Add(btn);
            btn.Click += new EventHandler(aBtn3_Click);

            Button btn2 = new Button();
            Image ant = Image.FromFile(System.Windows.Forms.Application.StartupPath + "\\image\\right.ico");
            btn2.Image = ant;
            btn2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            btn2.BackColor = System.Drawing.Color.Transparent;
            btn2.Name = "AntiClockwiseBtnSJ";
            btn2.Size = new System.Drawing.Size(47, 36);
            btn2.Location = new System.Drawing.Point(55, 445);
            Page.Controls.Add(btn2);
            btn2.Click += new EventHandler(aBtn4_Click);
            #endregion
        }
        private void xtraTabControl5_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
        {
            XtraTabPage Page = xtraTabControl5.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDic)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    pic = PictureDic[item.Key];
                }
            }
            pic.MouseDown += new System.Windows.Forms.MouseEventHandler(pic_MouseDown);
            pic.MouseMove += new System.Windows.Forms.MouseEventHandler(pic_MouseMove);
            pic.MouseUp += new System.Windows.Forms.MouseEventHandler(pic_MouseUp);
            pic.MouseWheel += new MouseEventHandler(pic_MouseWheel);
            Page.MouseDown += new System.Windows.Forms.MouseEventHandler(Page_MouseDown);
            Page.MouseUp += new System.Windows.Forms.MouseEventHandler(Page_MouseUp);
            Page.MouseMove += new System.Windows.Forms.MouseEventHandler(Page_MouseMove);

            #region 动态生成旋转按钮
            Page = xtraTabControl5.SelectedTabPage;
            if (Page == null)
                return;

            Button btn = new Button();
            Image clo = Image.FromFile(System.Windows.Forms.Application.StartupPath + "\\image\\left.ico");
            btn.Image = clo;
            btn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            btn.BackColor = System.Drawing.Color.Transparent;
            btn.Name = "ClockwiseBtn";
            btn.Size = new Size(47, 36);
            btn.Location = new Point(5, 445);
            Page.Controls.Add(btn);
            btn.Click += new EventHandler(aBtn5_Click);

            Button btn2 = new Button();
            Image ant = Image.FromFile(System.Windows.Forms.Application.StartupPath + "\\image\\right.ico");
            btn2.Image = ant;
            btn2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            btn2.BackColor = System.Drawing.Color.Transparent;
            btn2.Name = "AntiClockwiseBtn";
            btn2.Size = new System.Drawing.Size(47, 36);
            btn2.Location = new System.Drawing.Point(55, 445);
            Page.Controls.Add(btn2);
            btn2.Click += new EventHandler(aBtn6_Click);
            #endregion
        }
        private void xtraTabControl4_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
        {
            XtraTabPage Page = xtraTabControl4.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDicSJ)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    picSJ = PictureDicSJ[item.Key];
                }
            }
            picSJ.MouseDown += new System.Windows.Forms.MouseEventHandler(picSJ_MouseDown);
            picSJ.MouseMove += new System.Windows.Forms.MouseEventHandler(picSJ_MouseMove);
            picSJ.MouseUp += new System.Windows.Forms.MouseEventHandler(picSJ_MouseUp);
            picSJ.MouseWheel += new MouseEventHandler(picSJ_MouseWheel);
            Page.MouseDown += new System.Windows.Forms.MouseEventHandler(PageSJ_MouseDown);
            Page.MouseUp += new System.Windows.Forms.MouseEventHandler(PageSJ_MouseUp);
            Page.MouseMove += new System.Windows.Forms.MouseEventHandler(PageSJ_MouseMove);

            #region 动态生成旋转按钮
            Page = xtraTabControl4.SelectedTabPage;
            if (Page == null)
                return;

            Button btn = new Button();
            Image clo = Image.FromFile(System.Windows.Forms.Application.StartupPath + "\\image\\left.ico");
            btn.Image = clo;
            btn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            btn.BackColor = System.Drawing.Color.Transparent;
            btn.Name = "ClockwiseBtnSJ";
            btn.Size = new Size(47, 36);
            btn.Location = new Point(5, 445);
            Page.Controls.Add(btn);
            btn.Click += new EventHandler(aBtn7_Click);

            Button btn2 = new Button();
            Image ant = Image.FromFile(System.Windows.Forms.Application.StartupPath + "\\image\\right.ico");
            btn2.Image = ant;
            btn2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            btn2.BackColor = System.Drawing.Color.Transparent;
            btn2.Name = "AntiClockwiseBtnSJ";
            btn2.Size = new System.Drawing.Size(47, 36);
            btn2.Location = new System.Drawing.Point(55, 445);
            Page.Controls.Add(btn2);
            btn2.Click += new EventHandler(aBtn8_Click);
            #endregion
        }
        #endregion
        #region 图片旋转
        private void aBtn_Click(object sender, EventArgs e)
        {
            angle += 90;//每次增加90度
            XtraTabPage Page = xtraTabControl2.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDic)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    pic = PictureDic[item.Key];
                    foreach (var bmp in BitDic)
                    {
                        if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                        {
                            myBmp = BitDic[item.Key];
                            pic.Image = picRotate(myBmp, angle);//将旋转后的图片设置为picturebox背景
                            break;
                        }
                    }

                }
            }

            //顺时针旋转

            if (angle >= 360)
            {
                angle = 0;
            }

            GC.Collect();
        }
        private void aBtn2_Click(object sender, EventArgs e)
        {
            angle -= 90;//每次减少90度
            if (angle == 0)
            {
                angle = 360;
            }
            if (angle < 0)
            {
                angle = 270;
            }

            XtraTabPage Page = xtraTabControl2.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDic)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    pic = PictureDic[item.Key];
                    foreach (var bmp in BitDic)
                    {
                        if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                        {
                            myBmp = BitDic[item.Key];
                            pic.Image = picRotate(myBmp, angle);//将旋转后的图片设置为picturebox背景
                            break;
                        }
                    }

                }
            }
            GC.Collect();
        }
        private void aBtn3_Click(object sender, EventArgs e)
        {
            angle += 90;//每次增加90度
            XtraTabPage Page = xtraTabControl3.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDicSJ)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    picSJ = PictureDicSJ[item.Key];
                    foreach (var bmp in BitDicSJ)
                    {
                        if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                        {
                            myBmp = BitDicSJ[item.Key];
                            picSJ.Image = picRotate(myBmp, angle);//将旋转后的图片设置为picturebox背景
                            break;
                        }
                    }

                }
            }

            //顺时针旋转

            if (angle >= 360)
            {
                angle = 0;
            }

            GC.Collect();
        }
        private void aBtn4_Click(object sender, EventArgs e)
        {
            angle -= 90;//每次减少90度
            if (angle == 0)
            {
                angle = 360;
            }
            if (angle < 0)
            {
                angle = 270;
            }

            XtraTabPage Page = xtraTabControl3.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDicSJ)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    picSJ = PictureDicSJ[item.Key];
                    foreach (var bmp in BitDicSJ)
                    {
                        if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                        {
                            myBmp = BitDicSJ[item.Key];
                            picSJ.Image = picRotate(myBmp, angle);//将旋转后的图片设置为picturebox背景
                            break;
                        }
                    }

                }
            }
            GC.Collect();
        }

        private void aBtn5_Click(object sender, EventArgs e)
        {
            angle += 90;//每次增加90度
            XtraTabPage Page = xtraTabControl4.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDic)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    pic = PictureDic[item.Key];
                    foreach (var bmp in BitDic)
                    {
                        if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                        {
                            myBmp = BitDic[item.Key];
                            pic.Image = picRotate(myBmp, angle);//将旋转后的图片设置为picturebox背景
                            break;
                        }
                    }

                }
            }

            //顺时针旋转

            if (angle >= 360)
            {
                angle = 0;
            }

            GC.Collect();
        }
        private void aBtn6_Click(object sender, EventArgs e)
        {
            angle -= 90;//每次减少90度
            if (angle == 0)
            {
                angle = 360;
            }
            if (angle < 0)
            {
                angle = 270;
            }

            XtraTabPage Page = xtraTabControl4.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDic)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    pic = PictureDic[item.Key];
                    foreach (var bmp in BitDic)
                    {
                        if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                        {
                            myBmp = BitDic[item.Key];
                            pic.Image = picRotate(myBmp, angle);//将旋转后的图片设置为picturebox背景
                            break;
                        }
                    }

                }
            }
            GC.Collect();
        }
        private void aBtn7_Click(object sender, EventArgs e)
        {
            angle += 90;//每次增加90度
            XtraTabPage Page = xtraTabControl5.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDicSJ)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    picSJ = PictureDicSJ[item.Key];
                    foreach (var bmp in BitDicSJ)
                    {
                        if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                        {
                            myBmp = BitDicSJ[item.Key];
                            picSJ.Image = picRotate(myBmp, angle);//将旋转后的图片设置为picturebox背景
                            break;
                        }
                    }

                }
            }

            //顺时针旋转

            if (angle >= 360)
            {
                angle = 0;
            }

            GC.Collect();
        }
        private void aBtn8_Click(object sender, EventArgs e)
        {
            angle -= 90;//每次减少90度
            if (angle == 0)
            {
                angle = 360;
            }
            if (angle < 0)
            {
                angle = 270;
            }

            XtraTabPage Page = xtraTabControl5.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDicSJ)
            {
                if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                {
                    picSJ = PictureDicSJ[item.Key];
                    foreach (var bmp in BitDicSJ)
                    {
                        if (item.Key.Substring(item.Key.Length - 1, 1) == Page.Name.Substring(Page.Name.Length - 1, 1))
                        {
                            myBmp = BitDicSJ[item.Key];
                            picSJ.Image = picRotate(myBmp, angle);//将旋转后的图片设置为picturebox背景
                            break;
                        }
                    }

                }
            }
            GC.Collect();
        }
        //使图片旋转的方法
        public static Bitmap picRotate(Bitmap b, int angle)
        {

            angle = angle % 360;            //弧度转换
            double radian = angle * Math.PI / 180.0;
            double cos = Math.Cos(radian);
            double sin = Math.Sin(radian);
            //原图的宽和高
            int w = b.Width;
            int h = b.Height;
            int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
            int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
            //目标位图
            // Image dsImage = new Bitmap(W, H);
            Bitmap dsImage = new Bitmap(W, H);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dsImage);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //计算偏移量
            Point Offset = new Point((W - w) / 2, (H - h) / 2);
            //构造图像显示区域：让图像的中心与窗口的中心点一致
            Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);
            Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
            g.TranslateTransform(center.X, center.Y);
            g.RotateTransform(360 - angle);
            //恢复图像在水平和垂直方向的平移
            g.TranslateTransform(-center.X, -center.Y);
            g.DrawImage(b, rect);
            //重至绘图的所有变换
            g.ResetTransform();
            g.Save();
            g.Dispose();
            //dsImage.Save("yuancd.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            // g.DrawImage(b, new Point(0, 0));
            return dsImage;
        }
        #endregion
        #region 标准图纸缩放平移
        //鼠标按下功能
        private void pic_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
                isMove = true;
                pic.Focus();//
            }
        }
        //松开鼠标
        private void pic_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMove = false;
            }
        }
        //鼠标移动
        private void pic_MouseMove(object sender, MouseEventArgs e)
        {
            pic.Focus();//
            if (isMove)
            {
                int x, y;
                int moveX, moveY;
                moveX = Cursor.Position.X - mouseDownPoint.X;
                moveY = Cursor.Position.Y - mouseDownPoint.Y;
                x = pic.Location.X + moveX;
                y = pic.Location.Y + moveY;
                pic.Location = new Point(x, y);
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
            }
        }
        //鼠标滚轮滚动功能
        private void pic_MouseWheel(object sender, MouseEventArgs e)
        {
            int x = e.Location.X;
            int y = e.Location.Y;
            int ow = pic.Width;
            int oh = pic.Height;
            int VX, VY;
            if (e.Delta > 0)
            {
                pic.Width += zoomStep;
                pic.Height += zoomStep;

                PropertyInfo pInfo = pic.GetType().GetProperty("ImageRectangle", BindingFlags.Instance |
                    BindingFlags.NonPublic);
                Rectangle rect = (Rectangle)pInfo.GetValue(pic, null);

                pic.Width = rect.Width;
                pic.Height = rect.Height;
            }
            if (e.Delta < 0)
            {

                if (pic.Width < myBmp.Width / 10)
                    return;

                pic.Width -= zoomStep;
                pic.Height -= zoomStep;
                PropertyInfo pInfo = pic.GetType().GetProperty("ImageRectangle", BindingFlags.Instance |
                    BindingFlags.NonPublic);
                Rectangle rect = (Rectangle)pInfo.GetValue(pic, null);
                pic.Width = rect.Width;
                pic.Height = rect.Height;
            }

            VX = (int)((double)x * (ow - pic.Width) / ow);
            VY = (int)((double)y * (oh - pic.Height) / oh);
            pic.Location = new Point(pic.Location.X + VX, pic.Location.Y + VY);

        }
        private void Page_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
                isMove = true;
            }
        }

        private void Page_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMove = false;
            }
        }

        private void Page_MouseMove(object sender, MouseEventArgs e)
        {

            Page.Focus();
            if (isMove)
            {
                int x, y;
                int moveX, moveY;
                moveX = Cursor.Position.X - mouseDownPoint.X;
                moveY = Cursor.Position.Y - mouseDownPoint.Y;
                x = pic.Location.X + moveX;
                y = pic.Location.Y + moveY;
                pic.Location = new Point(x, y);
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
            }
        }
        #endregion
        #region SJ标准图纸缩放平移
        //鼠标按下功能
        private void picSJ_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
                isMove = true;
                picSJ.Focus();//
            }
        }
        //松开鼠标
        private void picSJ_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMove = false;
            }
        }
        //鼠标移动
        private void picSJ_MouseMove(object sender, MouseEventArgs e)
        {
            picSJ.Focus();//
            if (isMove)
            {
                int x, y;
                int moveX, moveY;
                moveX = Cursor.Position.X - mouseDownPoint.X;
                moveY = Cursor.Position.Y - mouseDownPoint.Y;
                x = picSJ.Location.X + moveX;
                y = picSJ.Location.Y + moveY;
                picSJ.Location = new Point(x, y);
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
            }
        }
        //鼠标滚轮滚动功能
        private void picSJ_MouseWheel(object sender, MouseEventArgs e)
        {
            int x = e.Location.X;
            int y = e.Location.Y;
            int ow = picSJ.Width;
            int oh = picSJ.Height;
            int VX, VY;
            if (e.Delta > 0)
            {
                picSJ.Width += zoomStep;
                picSJ.Height += zoomStep;

                PropertyInfo pInfo = picSJ.GetType().GetProperty("ImageRectangle", BindingFlags.Instance |
                    BindingFlags.NonPublic);
                Rectangle rect = (Rectangle)pInfo.GetValue(picSJ, null);

                picSJ.Width = rect.Width;
                picSJ.Height = rect.Height;
            }
            if (e.Delta < 0)
            {

                if (picSJ.Width < myBmp.Width / 10)
                    return;

                picSJ.Width -= zoomStep;
                picSJ.Height -= zoomStep;
                PropertyInfo pInfo = picSJ.GetType().GetProperty("ImageRectangle", BindingFlags.Instance |
                    BindingFlags.NonPublic);
                Rectangle rect = (Rectangle)pInfo.GetValue(picSJ, null);
                picSJ.Width = rect.Width;
                picSJ.Height = rect.Height;
            }

            VX = (int)((double)x * (ow - picSJ.Width) / ow);
            VY = (int)((double)y * (oh - picSJ.Height) / oh);
            picSJ.Location = new Point(picSJ.Location.X + VX, picSJ.Location.Y + VY);

        }
        private void PageSJ_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
                isMove = true;
            }
        }

        private void PageSJ_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMove = false;
            }
        }

        private void PageSJ_MouseMove(object sender, MouseEventArgs e)
        {

            Page.Focus();
            if (isMove)
            {
                int x, y;
                int moveX, moveY;
                moveX = Cursor.Position.X - mouseDownPoint.X;
                moveY = Cursor.Position.Y - mouseDownPoint.Y;
                x = picSJ.Location.X + moveX;
                y = picSJ.Location.Y + moveY;
                picSJ.Location = new Point(x, y);
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
            }
        }
        #endregion
        #region 动态生成Tab页和图片
        /// <summary>
        /// 新增选项卡页
        /// </summary>
        /// <param name="tabControl">选项卡控件</param>
        /// <param name="tabPageName">当期选项卡页name名称</param>
        /// <param name="tabText">当前选项卡页Text标题</param>
        /// <param name="newFormName">当前选项卡中的新窗体</param>
        public void AddTabpage(XtraTabControl tabControl, string tabPageName, string tabText, string newFormName, string pictureName)
        {
            if (IsTabpageExsit(tabControl, tabPageName))
            {
                return;
            }
            Page = new XtraTabPage();
            Page.Name = tabPageName;
            Page.Text = tabText;
            Page.Tooltip = tabPageName;

            Page.Controls.Add(AddNewForm(newFormName, pictureName));
            tabControl.TabPages.Add(Page);
            TabPageDic.Add(tabPageName, Page);
            tabControl.SelectedTabPage = Page;
            //Page.Controls.Add(AddNewForm(newFormName));
        }
        public void AddTabpageSJ(XtraTabControl tabControl, string tabPageName, string tabText, string newFormName, string pictureName)
        {
            if (IsTabpageExsitSJ(tabControl, tabPageName))
            {
                return;
            }
            Page = new XtraTabPage();
            Page.Name = tabPageName;
            Page.Text = tabText;
            Page.Tooltip = tabPageName;

            Page.Controls.Add(AddNewFormSJ(newFormName, pictureName));
            tabControl.TabPages.Add(Page);
            TabPageDicSJ.Add(tabPageName, Page);
            tabControl.SelectedTabPage = Page;
            //Page.Controls.Add(AddNewForm(newFormName));
        }
        /// <summary>
        /// 判断选项卡是否已经存在
        /// </summary>
        /// <param name="tabControl">选项卡控件</param>
        /// <param name="tabPageName">选项卡名称</param>
        /// <returns></returns>
        private bool IsTabpageExsit(XtraTabControl tabControl, string tabPageName)
        {
            foreach (var item in TabPageDic)
            {
                if (item.Key == tabPageName)
                {
                    tabControl.SelectedTabPage = item.Value;
                    return true;
                }
            }
            return false;
        }
        private bool IsTabpageExsitSJ(XtraTabControl tabControl, string tabPageName)
        {
            foreach (var item in TabPageDicSJ)
            {
                if (item.Key == tabPageName)
                {
                    tabControl.SelectedTabPage = item.Value;
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 在选项卡中生成图片
        /// </summary>
        /// <param name="form">图片名称</param>
        private PictureBox AddNewForm(string formName, string pictureName)
        {
            pic = new PictureBox();
            if (pictureName != "")
            {
                string filename = pictureName;
                myBmp = new Bitmap(filename);
                pic.Name = formName;
                pic.Location = new System.Drawing.Point(25, 4);
                pic.Size = new System.Drawing.Size(470, 410);//100,50
                pic.TabIndex = 0;
                pic.TabStop = false;
                pic.Image = myBmp;
                pic.SizeMode = PictureBoxSizeMode.Zoom; //设置picturebox为缩放模式Zoom
                //pic.Width = 1033;//myBmp.Width;
                //pic.Height = 358;//myBmp.Height;
                PictureDic.Add(formName, pic);
                BitDic.Add(formName, myBmp);
            }
            return pic;
        }
        private PictureBox AddNewFormSJ(string formName, string pictureName)
        {
            picSJ = new PictureBox();
            if (pictureName != "")
            {
                string filename = pictureName;
                myBmp = new Bitmap(filename);
                picSJ.Name = formName;
                picSJ.Location = new System.Drawing.Point(25, 4);
                picSJ.Size = new System.Drawing.Size(470, 410);//100,50
                picSJ.TabIndex = 0;
                picSJ.TabStop = false;
                picSJ.Image = myBmp;
                picSJ.SizeMode = PictureBoxSizeMode.Zoom; //设置picturebox为缩放模式Zoom
                //pic.Width = 1033;//myBmp.Width;
                //pic.Height = 358;//myBmp.Height;
                PictureDicSJ.Add(formName, picSJ);
                BitDicSJ.Add(formName, myBmp);
            }
            return picSJ;
        }
        #endregion

       
    }
}
